<script lang="ts" setup>
import { ref, watch } from 'vue';

import { VbenModal } from '@vben/common-ui';

import { Button, Input, message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getProductList } from '#/api/product/product';

// 定义产品类型
interface ProductItem {
  product_id: number | string;
  sku: string;
  name: string;
  spc: string;
  unit_pr: string;
  product_type?: string;
}

// 定义组件类型
interface ComponentItem {
  material_id: number | string;
  material_code: string;
  material_name: string;
  specification: string;
  unit: string;
}

// 定义props
interface Props {
  visible: boolean;
}

// 定义emits
interface Emits {
  (e: 'update:visible', value: boolean): void;
  (e: 'confirm', selectedComponents: ComponentItem[]): void;
}

const props = withDefaults(defineProps<Props>(), {});

const emit = defineEmits<Emits>();

// 表格相关
const selectedComponents = ref<ComponentItem[]>([]);
const searchKeyword = ref('');

// 使用vben的表格组件
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: [
      { type: 'checkbox', width: 60 },
      { field: 'sku', title: '产品编码', width: 150 },
      { field: 'name', title: '产品名称', width: 200 },
      { field: 'spc', title: '规格型号', width: 200 },
      { field: 'unit_pr', title: '单位', width: 100 },
      { field: 'product_type', title: '产品类型', width: 120 },
      {
        field: 'action',
        title: '操作',
        width: 100,
      },
    ],
    height: 400,
    checkboxConfig: {
      highlight: true,
      range: true,
    },
    proxyConfig: {
      autoLoad: false, // 禁用自动加载，手动控制
      ajax: {
        query: async () => {
          try {
            gridApi.setLoading(true);
            const params = {
              page: 1,
              pageSize: 1000,
              search: searchKeyword.value || undefined,
            };
            const response = await getProductList(params);
            // requestClient已经处理了响应格式，直接返回items和total
            return {
              items: response.items || [],
              total: response.total || 0,
            };
          } catch (error) {
            console.error('获取产品列表失败:', error);
            message.error('获取产品列表失败');
            return {
              items: [],
              total: 0,
            };
          } finally {
            gridApi.setLoading(false);
          }
        },
      },
    },
  },
});

// 监听props变化
watch(
  () => props.visible,
  (val) => {
    if (val) {
      // 模态框打开时加载数据
      gridApi.reload();
    }
  },
);

// 监听搜索关键词变化
watch(
  searchKeyword,
  () => {
    // 防抖处理，避免频繁请求
    setTimeout(() => {
      if (props.visible) {
        gridApi.reload();
      }
    }, 300);
  },
);

// 判断是否已选择
const isSelected = (row: ProductItem) => {
  return selectedComponents.value.some(
    (item) => item.material_id === row.product_id,
  );
};

// 选择产品
const handleSelect = (row: ProductItem) => {
  const index = selectedComponents.value.findIndex(
    (item) => item.material_id === row.product_id,
  );
  if (index > -1) {
    selectedComponents.value.splice(index, 1);
  } else {
    selectedComponents.value.push({
      material_id: row.product_id,
      material_code: row.sku,
      material_name: row.name,
      specification: row.spc,
      unit: row.unit_pr,
    });
  }
};

// 取消
const handleCancel = () => {
  emit('update:visible', false);
};

// 确认
const handleConfirm = () => {
  if (selectedComponents.value.length === 0) {
    message.warning('请至少选择一个组件');
    return;
  }
  emit('confirm', selectedComponents.value);
  emit('update:visible', false);
};
</script>

<template>
  <VbenModal
    :visible="visible"
    title="选择组件"
    :width="1000"
    @cancel="handleCancel"
    @confirm="handleConfirm"
  >
    <div class="mb-4">
      <Input
        v-model:value="searchKeyword"
        placeholder="请输入产品编码或名称搜索"
        allow-clear
        style="width: 300px"
      />
    </div>
    <Grid>
      <template #action="scope">
        <Button
          type="link"
          :danger="isSelected(scope.row)"
          @click="handleSelect(scope.row)"
        >
          {{ isSelected(scope.row) ? '已选择' : '选择' }}
        </Button>
      </template>
    </Grid>
  </VbenModal>
</template>
